package com.zsck.pos.activity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewStub;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.chinaums.commoncheck.R;
import com.ums.AppHelper;
import com.ums.anypay.service.IOnTransEndListener;
import com.zsck.pos.adapter.BillAdapter;
import com.zsck.pos.adapter.ProjectAdapter;
import com.zsck.pos.base.BaseTitleActivity;
import com.zsck.pos.bean.Bill;
import com.zsck.pos.bean.Bills;
import com.zsck.pos.bean.PaySuccess;
import com.zsck.pos.bean.PosResult;
import com.zsck.pos.bean.Project;
import com.zsck.pos.bean.TransData;
import com.zsck.pos.bean.UncheckBill;
import com.zsck.pos.common.Constants;
import com.zsck.pos.net.MyObserver;
import com.zsck.pos.net.NetConfig;
import com.zsck.pos.net.RetrofitCilent;
import com.zsck.pos.utils.KeyBoardUtils;
import com.zsck.pos.utils.LogUtil;
import com.zsck.pos.utils.SharePreferenceUtils;
import com.zsck.pos.view.RefreshListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.zsck.net.Utils.RxHelper.observableIO2Main;

public class BillsActivity extends BaseTitleActivity implements AdapterView.OnItemClickListener, TextWatcher, TextView.OnEditorActionListener, RefreshListView.OnRefreshListener, AdapterView.OnItemSelectedListener {
    /*下拉选择*/
    @BindView(R.id.sp_project)
    Spinner mSpProject;
    /*搜索框*/
    @BindView(R.id.et_search)
    EditText mEtSearch;
    /*删除*/
    @BindView(R.id.iv_delete)
    ImageView mIvDelete;
    /*删除*/
    @BindView(R.id.lv_list)
    RefreshListView mLvList;
    /*空*/
    @BindView(R.id.ll_empty)
    LinearLayout mLlEmpty;

    private int page = 1;

    private List<Bill> mListData = new ArrayList<>();

    private String mCondition;

    private BillAdapter adapter;
    /*是否有更多数据*/
    private boolean hasMore = true;


    private Project mProject;


    @Override
    public int setLayout() {
        return R.layout.activity_bills;
    }

    @Override
    public String setTitle() {
        return "账单查询";
    }

    @Override
    public Activity setActivity() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        initEvents();
        initData();
    }


    private void initEvents() {
        mIvDelete.setOnClickListener(this);
        mLvList.setOnItemClickListener(this);
        mEtSearch.setOnEditorActionListener(this);
        mEtSearch.addTextChangedListener(this);
        mLvList.setOnRefreshListener(this);
        mSpProject.setOnItemSelectedListener(this);
    }

    private void initData() {
        mLvList.addHeaderView(new ViewStub(this));
        mLvList.addFooterView(new ViewStub(this));
        String keyword = mEtSearch.getText().toString();
        adapter = new BillAdapter(this, mListData, keyword);
        mLvList.setAdapter(adapter);
//        if(NetConfig.projects == null){
        getProjectAppSelectList();
//        }else{
//            initSpinner();
//        }

       /* if (NetConfig.projects != null && NetConfig.projects.get(0) != null) {
            Project project = NetConfig.projects.get(0);
            getUnCheckBilllist(project.getId());
        }*/
    }

    @Override
    protected void onResume() {
        super.onResume();
//        getProjectAppSelectList();


    }

    private void initSpinner() {
        if (NetConfig.projects == null || NetConfig.projects.size() == 0) {
            return;
        }
        mProject = NetConfig.projects.get(0);
        ProjectAdapter adapter = new ProjectAdapter(this, NetConfig.projects);
//        ArrayAdapter<Project> adapter = new ArrayAdapter<Project>(this, R.layout.spinner_item, NetConfig.projects);
//        adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
        mSpProject.setAdapter(adapter);
        String projectId = SharePreferenceUtils.getString(this, "projectId");
        if (TextUtils.isEmpty(projectId)) {
            return;
        }
        for (int i = 0; i < NetConfig.projects.size(); i++) {
            Project project = NetConfig.projects.get(i);
            if (projectId.equals(project.getId())) {
                mProject = project;
                mSpProject.setSelection(i);
                break;
            }
        }

    }


    private void getProjectAppSelectList() {
        String possn = SharePreferenceUtils.getString(this, "POSSN");
        Map<String, Object> map = new HashMap<>();
        if (!TextUtils.isEmpty(possn)) {
            map.put("posId", possn);
        }
        MyObserver<List<Project>> observer = new MyObserver<List<Project>>(this) {
            @Override
            public void onSuccess(List<Project> result) {
                if (result != null && result.size() > 0) {
                    NetConfig.projects = result;
                    initSpinner();
                } else {
                    mLvList.setVisibility(View.GONE);
                    mLlEmpty.setVisibility(View.VISIBLE);
                    Toast.makeText(BillsActivity.this, "没有项目权限", Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                LogUtil.e("test", e.getMessage());
            }

            @Override
            public void reRequest() {
                getProjectAppSelectList();
            }
        };
        /*RetrofitCilent.getApiService().getProjectAppSelectList(map).
                compose(observableIO2Main(this)).subscribe(observer);*/
        RetrofitCilent.getApiService().queryProject(map).
                compose(observableIO2Main(this)).subscribe(observer);
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_delete:
                mEtSearch.setText(null);
                break;
            case R.id.rl_back:

                break;
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        page = 1;
        getPageBillList();
    }

    private void getPageBillList() {
        Map<String, Object> map = new HashMap<>();
        map.put("condition", mCondition);
        if (mProject == null) {
            Toast.makeText(BillsActivity.this, "无项目权限，无法查询账单", Toast.LENGTH_SHORT).show();
            return;
        }
        map.put("projectId", mProject.getId());
        map.put("currentPage", page);
        map.put("pageSize", 10);
        MyObserver<Bills> observer = new MyObserver<Bills>(this) {
            @Override
            public void onSuccess(Bills result) {
                onBillList(result);
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                mLvList.refreshComplete(false);
                LogUtil.e("test", e.getMessage());
                Toast.makeText(BillsActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void reRequest() {
                getPageBillList();
            }
        };
        RetrofitCilent.getApiService().getPageBillList(map).
                compose(observableIO2Main(this)).subscribe(observer);
    }


    private void onBillList(Bills result) {
        mLvList.refreshComplete(true);
        if (page == 1) {
            if (result == null || result.getRows() == null || result.getRows().size() == 0) {
                mLvList.setVisibility(View.GONE);
                mLlEmpty.setVisibility(View.VISIBLE);
                hasMore = false;
                return;
            }
        } else if (result == null || result.getRows() == null || result.getRows().size() < 10) {
            hasMore = false;
        }


        mLvList.setVisibility(View.VISIBLE);
        mLlEmpty.setVisibility(View.GONE);
        if (page == 1) {
            mListData.clear();
        }
        mListData.addAll(result.getRows());
        adapter.setKeyword(mEtSearch.getText().toString());
        adapter.notifyDataSetChanged();
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent intent = new Intent(this, BillActivity.class);
        ComponentName componentName = new ComponentName("com.ums.sz.pos", "com.zsck.pos.activity.BillActivity");
        intent.setComponent(componentName);
        intent.putExtra("projectId",mProject.getId());
        intent.putExtra("idList", new Gson().toJson(mListData.get(position).getIdList()));
        startActivity(intent);

    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        mIvDelete.setVisibility(TextUtils.isEmpty(s) ? View.GONE : View.VISIBLE);
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        mCondition = mEtSearch.getText().toString();
        if (TextUtils.isEmpty(mCondition)) {
            return false;
        }
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            page = 1;
            hasMore = true;
            getPageBillList();
            KeyBoardUtils.hideByView(this, mEtSearch);
        }
        return false;
    }

    @Override
    public void onLoadMore() {
        if (!hasMore) {
            return;
        }
        page++;
        getPageBillList();
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        mProject = NetConfig.projects.get(position);
        SharePreferenceUtils.putString(this, "projectId", mProject.getId());
        page = 1;
        getPageBillList();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }


    /**
     * 查询所有不确定支付状态的订单
     */
    private void getUnCheckBilllist(String projectId) {
        Map<String, Object> map = new HashMap<>();
        map.put("projectId", projectId);
        MyObserver<List<UncheckBill>> observer = new MyObserver<List<UncheckBill>>(this) {
            @Override
            public void onSuccess(List<UncheckBill> result) {
                if (result != null) {
                    queryOrderDetail(result);
                }

            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                mLvList.refreshComplete(false);
                LogUtil.e("test", e.getMessage());
                Toast.makeText(BillsActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void reRequest() {
                getUnCheckBilllist(projectId);
            }
        };
        RetrofitCilent.getApiService().getUncheckBill(map).
                compose(observableIO2Main(this)).subscribe(observer);
    }


    private String appName = "公共资源";
    private String transId = "交易明细";
    private JSONObject transData = new JSONObject();
    List<UncheckBill> uncheckBills = new ArrayList<>();
    private boolean IsCallSuccess = false;

    /*查询订单支付明细*/
    private void queryOrderDetail(List<UncheckBill> results) {
        try {
            uncheckBills.clear();
            uncheckBills.addAll(results);

            for (UncheckBill uncheckBill : results) {
                transData.put("extOrderNo", uncheckBill.getExtOrderNo());
//                transData.put("traceNo", "000000");
                transData.put("appId", Constants.APPID);//appId
                transData.put("isNeedPrintReceipt", true);
                transData.put("isShowDetailPage", false);

                if(IsCallSuccess==false){
                    IsCallSuccess = !IsCallSuccess;
                    AppHelper.callTrans(this, appName, transId, transData, listener);
                }

            }


        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


    IOnTransEndListener listener = new IOnTransEndListener() {
        @Override
        public void onEnd(String reslutmsg) {//reslutmsg接口调用结果
            LogUtil.e("IOnTransEndListener", "IOnTransEndListener:" + reslutmsg);
            PosResult result = new Gson().fromJson(reslutmsg, PosResult.class);
            if (result == null) {
                LogUtil.i("PayActivity", "出错了");
                return;
            }
            TransData transData = result.getTransData();
            if (transData == null) {
                LogUtil.i("PayActivity", "出错了");
                return;
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    for (UncheckBill uncheckBill : uncheckBills) {
                        posPayCallback(result, uncheckBill);
                    }

                }
            });


        }
    };


    /**
     * 支付成功回调
     *
     * @param result
     */
    private void posPayCallback(PosResult result, UncheckBill uncheckBill) {
        Map<String, Object> map = new HashMap<>();
        TransData transData = result.getTransData();
        map.put("appName", transData.getTransName());
        map.put("feeList", uncheckBill.getFeeList());
        map.put("amt", (int) (transData.getAmt() * 100));
        map.put("resultCode", result.getResultCode());
        map.put("billIdList", uncheckBill.getBillIdList());
        map.put("resultMsg", result.getResultMsg());
        map.put("transData", new Gson().toJson(result.getTransData()));
        map.put("transId", transData.getTransName());
        map.put("payer", uncheckBill.getPayer());
        map.put("extOrderNo", transData.getTraceNo());

        MyObserver<PaySuccess> observer = new MyObserver<PaySuccess>(this) {
            @Override
            public void onSuccess(PaySuccess result) {
                IsCallSuccess=!IsCallSuccess;
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                LogUtil.e("test", errorMsg);
            }

            @Override
            public void reRequest() {
                posPayCallback(result, uncheckBill);
            }
        };
        RetrofitCilent.getApiService().posPayCallback(map).
                compose(observableIO2Main(this)).subscribe(observer);
    }
}
